package com.lipp.luosu.test.efftiveJava.asyc;

import java.util.concurrent.Semaphore;

/**
 * @ClassNameSemaphoreDemo
 * @description: TODO 类描述
 * @Author lipp
 * @Date 2024/2/2 14:13
 * @Version 1.0
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        // 创建一个容量为3的信号量
        Semaphore semaphore = new Semaphore(3);

        // 启动10个线程，但只有3个能同时执行
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    semaphore.acquire(); // 获取许可
                    executeTask(finalI);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    semaphore.release(); // 任务完成后释放许可
                }
            }).start();
        }
    }

    private static void executeTask(int taskId) {
        System.out.println("Task " + taskId + " started by " + Thread.currentThread().getName());
        try {
            Thread.sleep(1000); // 模拟耗时操作
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        System.out.println("Task " + taskId + " completed by " + Thread.currentThread().getName());
    }
}
